package com.howso.cloud.uaa.authentication.sms;


import com.howso.cloud.oauth2.token.MobileSmsAuthenticationToken;
import com.howso.cloud.uaa.service.IValidateCodeService;
import com.howso.cloud.uaa.service.impl.UserDetailServiceFactory;
import lombok.Setter;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;

@Setter
public class MobileSmsAuthenticationProvider implements AuthenticationProvider {
    private UserDetailServiceFactory userDetailsService;
    private IValidateCodeService validateCodeService;

    @Override
    public Authentication authenticate(Authentication authentication) {
        MobileSmsAuthenticationToken authenticationToken = (MobileSmsAuthenticationToken) authentication;
        String mobile = (String) authenticationToken.getPrincipal();
        String sms = (String) authenticationToken.getCredentials();
        UserDetails user = userDetailsService.getService().loadUserByMobile(mobile);
        if (user == null) {
            throw new InternalAuthenticationServiceException("手机号不存在");
        }
        validateCodeService.validate(mobile,sms);
        MobileSmsAuthenticationToken authenticationResult = new MobileSmsAuthenticationToken(user, sms, user.getAuthorities());
        authenticationResult.setDetails(authenticationToken.getDetails());
        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return MobileSmsAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
